public without sharing class RightsConfirmationListHandler {



	//审批通过之后 回写到 执行明细里
	public static void backToPerforance(List<RightsConfirmation__c> rcList ,Map<Id,RightsConfirmation__c> oldMap  ){


		Map<Id,Set<Id>> accUserMap = new Map<Id,Set<Id>>();

		Set<Id>userAll = new Set<Id>();
		Set<Id> sourceSet = new Set<Id>();
		Map<String,PerformanceRightsConfirmation__c> tmp = new Map<String,PerformanceRightsConfirmation__c>();
		for (RightsConfirmation__c rcl : rcList) {
			RightsConfirmation__c old = oldMap.get(rcl.Id);

			if(rcl.Status__c == '审批成功' && old.Status__c != rcl.Status__c ){

				System.debug('backToPerforance '+rcl );
				for (RightsConfirmationList__c rc  :[select Id ,TripartiteOwnerManager__c,TripartiteOwner__c,DistributionOwnerManager__c,Company__c,
						DistributionOwner__c,DirectBusinessOwnerManager__c,DirectBusinessOwner__c,Year__c ,Quarter__c,Account__c,TerminalAccount__c,
						AccountPK__c,TerminalPK__c,Province__c,
						BiochemicalIOwner__c,BiochemicalIOwnerManager__c,
						ImmunityOwner__c,ImmunityOwnerManager__c,
						ClinicalLaboratoryOwner__c,ClinicalLaboratoryOwnerManager__c,
						PathologyOwner__c,PathologyOwnerManager__c,
						POCTOwner__c,POCTOwnerManager__c, 
						BDOwnerManager__c,BDOwner__c,
						ProvinceManager__c,
						SysmexOwner__c,SysmexOwnerManager__c,
						MicrobeOwner__c,MicrobeOwnerManager__c,
						MolecularOwner__c,MolecularOwnerManager__c,

						TerminalAccountName__c,AccountName__c 
					from RightsConfirmationList__c where RightsConfirmation__c  =:rcl.Id  ] ) {
					String key1 = rc.Year__c +'-'+rc.Quarter__c+'-'+rc.AccountPK__c+'-'+rc.TerminalPK__c+'-'+rc.Company__c +'-'+rc.Province__c ;

					Set<Id>userset = new Set<Id>();
					PerformanceRightsConfirmation__c prc = new PerformanceRightsConfirmation__c();
					prc.RightsConfirmationList__c = rc.Id;
					sourceSet.add(rc.Id);
					prc.Only__c = key1 ; 
					prc.Account__c = rc.Account__c;
					prc.TerminalAccount__c = rc.TerminalAccount__c;
					prc.Province__c = rc.Province__c;
					//prc.ProductTpye__c = rc.ProductTpye__c;
					prc.Year__c = rc.Year__c;
					prc.Quarter__c = rc.Quarter__c;
					prc.Company__c = rc.Company__c;

					prc.TerminalAccountName__c = rc.TerminalAccountName__c;
					prc.TerminalPK__c = rc.TerminalPK__c;
					prc.AccountName__c = rc.AccountName__c;
					prc.AccountPK__c = rc.AccountPK__c;

					prc.ProvinceManager__c = rc.ProvinceManager__c;
					if(prc.ProvinceManager__c != null )userset.add(prc.ProvinceManager__c);


					prc.DistributionOwner__c = rc.DistributionOwner__c;
					if(prc.DistributionOwner__c != null )userset.add(prc.DistributionOwner__c);
					prc.DistributionOwnerManager__c = rc.DistributionOwnerManager__c;
					if(prc.DistributionOwnerManager__c != null )userset.add(prc.DistributionOwnerManager__c);

					prc.DirectBusinessOwner__c = rc.DirectBusinessOwner__c;
					if(prc.DirectBusinessOwner__c != null )userset.add(prc.DirectBusinessOwner__c);
					prc.DirectBusinessOwnerManager__c = rc.DirectBusinessOwnerManager__c;
					if(prc.DirectBusinessOwnerManager__c != null )userset.add(prc.DirectBusinessOwnerManager__c);

					prc.TripartiteOwnerManager__c = rc.TripartiteOwnerManager__c;
					if(prc.TripartiteOwnerManager__c != null )userset.add(prc.TripartiteOwnerManager__c);
					prc.TripartiteOwner__c = rc.TripartiteOwner__c ; 
					if(prc.TripartiteOwner__c != null )userset.add(prc.TripartiteOwner__c);

					//生化
					prc.BiochemicalIOwner__c = rc.BiochemicalIOwner__c ;
					if(prc.BiochemicalIOwner__c != null )userset.add(prc.BiochemicalIOwner__c);
					prc.BiochemicalIOwnerManager__c =  rc.BiochemicalIOwnerManager__c;
					if(prc.BiochemicalIOwnerManager__c != null )userset.add(prc.BiochemicalIOwnerManager__c);
					//免疫
					prc.ImmunityOwner__c = rc.ImmunityOwner__c ;
					if(prc.ImmunityOwner__c != null )userset.add(prc.ImmunityOwner__c);
					prc.ImmunityOwnerManager__c =  rc.ImmunityOwnerManager__c ;
					if(prc.ImmunityOwnerManager__c != null )userset.add(prc.ImmunityOwnerManager__c);
					//临检
					prc.ClinicalLaboratoryOwner__c =  rc.ClinicalLaboratoryOwner__c ;
					if(prc.ClinicalLaboratoryOwner__c != null )userset.add(prc.ClinicalLaboratoryOwner__c);
					prc.ClinicalLaboratoryOwnerManager__c =rc.ClinicalLaboratoryOwnerManager__c ;
					if(prc.ClinicalLaboratoryOwnerManager__c != null )userset.add(prc.ClinicalLaboratoryOwnerManager__c);
					//病理
					prc.PathologyOwner__c = rc.PathologyOwner__c ;
					if(prc.PathologyOwner__c != null )userset.add(prc.PathologyOwner__c);
					prc.PathologyOwnerManager__c =  rc.PathologyOwnerManager__c ;
					if(prc.PathologyOwnerManager__c != null )userset.add(prc.PathologyOwnerManager__c);

					//POCT
					prc.POCTOwner__c = rc.POCTOwner__c ;
					if(prc.POCTOwner__c != null )userset.add(prc.POCTOwner__c);
					prc.POCTOwnerManager__c =  rc.POCTOwnerManager__c ;
					if(prc.POCTOwnerManager__c != null )userset.add(prc.POCTOwnerManager__c);

					 //希森美康
					prc.SysmexOwner__c =  rc.SysmexOwner__c ;
		            if(prc.SysmexOwner__c != null )userset.add(prc.SysmexOwner__c);
					prc.SysmexOwnerManager__c =  rc.SysmexOwnerManager__c ;
		            if(prc.SysmexOwnerManager__c != null )userset.add(prc.SysmexOwnerManager__c);
		            //微生物
					prc.MicrobeOwner__c =  rc.MicrobeOwner__c ;
		            if(prc.MicrobeOwner__c != null )userset.add(prc.MicrobeOwner__c);
					prc.MicrobeOwnerManager__c =  rc.MicrobeOwnerManager__c ;
		            if(prc.MicrobeOwnerManager__c != null )userset.add(prc.MicrobeOwnerManager__c);

		            //BD
					prc.BDOwnerManager__c =  rc.BDOwnerManager__c ;
		            if(prc.BDOwnerManager__c != null )userset.add(prc.BDOwnerManager__c);
					prc.BDOwner__c =  rc.BDOwner__c ;
		            if(prc.BDOwner__c != null )userset.add(prc.BDOwner__c);

		            //分子产品
		            prc.MolecularOwnerManager__c = rc.MolecularOwnerManager__c ;
		            if(prc.MolecularOwnerManager__c != null )userset.add(prc.MolecularOwnerManager__c);

		             prc.MolecularOwner__c = rc.MolecularOwner__c ;
		            if(prc.MolecularOwner__c != null )userset.add(prc.MolecularOwner__c);
		            

					tmp.put(prc.Only__c,prc);

					Set<Id>tmpset1 = accUserMap.containsKey(prc.Account__c) ? accUserMap.get(prc.Account__c) : new Set<Id>();
					tmpset1.addAll(userset);
					if(prc.Account__c != null ) accUserMap.put(prc.Account__c , tmpset1);


					Set<Id>tmpset2 = accUserMap.containsKey(prc.TerminalAccount__c) ? accUserMap.get(prc.TerminalAccount__c) : new Set<Id>();
					tmpset2.addAll(userset);
					if(prc.TerminalAccount__c != null && prc.TerminalAccount__c != prc.Account__c )accUserMap.put(prc.TerminalAccount__c , tmpset2);


					userAll.addAll(userset);
				}	
			}
		}

		//通过唯一性匹配的结果 
		for (PerformanceRightsConfirmation__c prc  : [select Id ,Only__c ,RightsConfirmationList__c from PerformanceRightsConfirmation__c where Only__c in: tmp.keySet()] ) {
			if(tmp.containsKey(prc.Only__c))tmp.get(prc.Only__c).Id = prc.Id;

		}

		//通过 id 匹配的结果 存在 但不是在唯一性匹配的结果中 则为修改过的数据 要删除
		List<PerformanceRightsConfirmation__c> delPrcList =new List<PerformanceRightsConfirmation__c>();
		for (PerformanceRightsConfirmation__c prc  : [select Id ,Only__c ,RightsConfirmationList__c from PerformanceRightsConfirmation__c where RightsConfirmationList__c in:sourceSet  and Only__c not in:tmp.keySet() ] ) {
			delPrcList.add(prc);
		}

		Set<Id>incativeSet = new Set<Id>();
		for(User u :[select Id from User where Id in:userAll and IsActive != true   ]){
			incativeSet.add(u.Id);
		}
		// 删除之前的共享 增加新的共享
		List<AccountTeamMember> delList = new List<AccountTeamMember>();
		List<AccountTeamMember> atList = new List<AccountTeamMember>();
			//审批通过的时候 将销售员 匹配到客户的客户小组
			for (AccountTeamMember atm  : [select Id,UserId ,AccountId,Account.OwnerId ,TeamMemberRole from AccountTeamMember where AccountId in:accUserMap.keySet() ]) {
				//如果是所有人 
				if(accUserMap.containsKey(atm.AccountId) && accUserMap.get(atm.AccountId ).contains(atm.Account.OwnerId )) accUserMap.get(atm.AccountId ).remove(atm.Account.OwnerId);
				//如果是客户小组
				if(accUserMap.containsKey(atm.AccountId ) && accUserMap.get(atm.AccountId ).contains(atm.UserId) ){
					
					
					atm.TeamMemberRole = '销售绩效分配客户权限';
					accUserMap.get(atm.AccountId ).remove(atm.UserId);
					//如果该人员是离职人员
					if(incativeSet.contains(atm.UserId)) continue;
					atList.add(atm);
					continue;
				}
				//如果是之前的
				if(atm.TeamMemberRole == '销售绩效分配客户权限')delList.add(atm);
			}

		
        Set<Id> userset = new Set<Id>();

		for (Id accId :  accUserMap.keySet() ) {
			for (Id userId  : accUserMap.get(accId)) {
				//如果该人员是离职人员
				if(incativeSet.contains(userId)) continue;
				userset.add(userId);
				atList.add(new AccountTeamMember(AccountId=accId,UserId=userId ,TeamMemberRole = '销售绩效分配客户权限' ));
			}
		}

		 if(!delPrcList.isEmpty())delete delPrcList;
		if(!tmp.isEmpty()) upsert tmp.values()  ;
		if(!delList.isEmpty()) delete delList;
		if(!atList.isEmpty()) upsert atList;

		 List<AccountShare> ahList = new List<AccountShare>();
        for(AccountShare ah : [select Id , AccountAccessLevel ,CaseAccessLevel from AccountShare where AccountId in:accUserMap.keySet() and  RowCause = 'Team' and UserOrGroupId=:userset ] ){
            ah.AccountAccessLevel = 'Edit';
            ah.CaseAccessLevel = 'Read';
            ahList.add(ah);

        }
        update ahList;

	}

	///找到各省的所有人
	public static Map<String,String> getOwnerMap(){
		Map<String,String> provinceMap = new Map<String,String>();
		Map<String,Id> userMap = new Map<String,Id> ();

		for ( String d1 : Label.PerformanceRights.split(';')) {
			if(String.isBlank(d1) == false){
				String[] ss = d1.split('-');
				String  userno = ss[1];
				while(userno.length() < 4){
					userno = '0'+userno;
				}
				userMap.put(userno, null);
				provinceMap.put(ss[0],userno );
			}
		}
		for (User u  :[select Id,ExuserCode__c from User where ExuserCode__c in: userMap.keySet() and IsActive = true ] ) {
			userMap.put(u.ExuserCode__c,u.Id);
		}
		for (String key : provinceMap.keySet() ) {
			provinceMap.put(key, userMap.containsKey(provinceMap.get(key)) ? userMap.get(provinceMap.get(key)) : null );
		}
		return provinceMap;
	}
	//匹配人员和主表
	public static void matchPeople(List<RightsConfirmationList__c> rcList ){

		//匹配客户
		//获取唯一标识: 年度+季度+开票客户+终端客户+产品大类
		Map<String,Id> accMap = new Map<String,Id>();


		Map<String,PerformanceRightsConfirmation__c> prMap = new Map<String ,PerformanceRightsConfirmation__c>();

		Map<String ,List<RightsConfirmationList__c>> rMap = new Map<String,List<RightsConfirmationList__c>>(); 

		//Map<String,Id> exMap =new Map<String,Id>();

		for (RightsConfirmationList__c rc  : rcList ) {
				
				if(rc.AccountPK__c != null )accMap.put(rc.AccountPK__c, null);
					
					
					
				
				if(rc.TerminalPK__c != null )accMap.put(rc.TerminalPK__c, null);

					
				
				
				//String key1 = rc.Year__c +'-'+rc.Quarter__c+'-'+rc.AccountPK__c+'-'+rc.TerminalPK__c+'-'+rc.ProductTpye__c ;

				//exMap.put(key1 , null);
				// 上季度年份+上季度 +开票客户+终端客户+产品大类
				String key = getLastQuaterYear(rc.Year__c,rc.Quarter__c) +'-'+getLastQuater(rc.Quarter__c)+'-'+rc.AccountPK__c+'-'+rc.TerminalPK__c+'-'+rc.Company__c+'-'+rc.Province__c ;

				//年 + 季度 + 省份
				String mainKey  =rc.Year__c +'-'+rc.Quarter__c+'-'+rc.Province__c+'-'+rc.Company__c;

				prMap.put(key, null);

				List<RightsConfirmationList__c> tmp = rMap.containsKey(mainKey) ? rMap.get(mainKey) : new List<RightsConfirmationList__c>();
				tmp.add(rc);
				rMap.put(mainKey, tmp);


		}
		
		//匹配已经存在的明细
		/*for (RightsConfirmationList__c rc  :[select Id ,Only__c from RightsConfirmationList__c  where Only__c in: exMap.keySet()] ) {
			exMap.put(rc.Only__c , rc.Id);
		}*/




		//匹配客户
		Map<String,Id> accIdMap = new Map<String,Id>();
		for (Account  acc   : [select Id,NCICCode__c from Account where NCICCode__c in: accMap.keySet() or Id in: accMap.keySet()]) {
			
			accMap.put(acc.NCICCode__c, acc.Id);
			accIdMap.put(acc.Id , acc.Id);

		}
		//匹配主表
		Map<String ,Id > mainMap =new Map<String,Id>();
		for (RightsConfirmation__c rcf  : [select Id ,Only__c from RightsConfirmation__c where Only__c in: rMap.keySet()] ) {
			mainMap.put(rcf.Only__c , rcf.Id);
		}
		//匹配 人员
		for ( PerformanceRightsConfirmation__c prc : [select Id ,Only__c,TripartiteOwnerManager__c,TripartiteOwner__c,
	 		DirectBusinessOwnerManager__c,DirectBusinessOwner__c,
	 		DistributionOwner__c,DistributionOwnerManager__c,
	 		BiochemicalIOwner__c,BiochemicalIOwnerManager__c,
	 		ImmunityOwner__c,ImmunityOwnerManager__c,
	 		ClinicalLaboratoryOwner__c,ClinicalLaboratoryOwnerManager__c,
	 		PathologyOwner__c,PathologyOwnerManager__c,
	 		POCTOwner__c,POCTOwnerManager__c,
	 		SysmexOwner__c,SysmexOwnerManager__c,
	 		MicrobeOwner__c,MicrobeOwnerManager__c,
			BDOwnerManager__c,BDOwner__c,
			MolecularOwner__c,MolecularOwnerManager__c,
	 		ProvinceManager__c

		 from PerformanceRightsConfirmation__c where Only__c in: prMap.keySet()] ) {
			
			prMap.put(prc.Only__c , prc );

		}

		Map<String,RightsConfirmation__c> mainRCMap =new Map<String,RightsConfirmation__c>();
		Map<String,String>provinceMap = getOwnerMap();
		for (String mainKey : rMap.keySet() ) {
			

			if(!mainMap.containsKey(mainKey)){
				RightsConfirmationList__c rc = rMap.get(mainKey)[0];
				RightsConfirmation__c rcM = new RightsConfirmation__c(Only__c= mainKey,Company__c=rc.Company__c, Quarter__c=rc.Quarter__c, Year__c =rc.Year__c , Province__c=rc.Province__c  );
				
				if(rcm.Company__c != null && provinceMap.containsKey(rcM.Company__c)){

					rcM.OwnerId = provinceMap.get(rcM.Company__c);
					
				}
				if( rcM.OwnerId == null && rcM.Province__c != null && provinceMap.containsKey(rcM.Province__c)){

					rcM.OwnerId = provinceMap.get(rcM.Province__c);
				}
				mainRCMap.put(mainKey,rcM);
				
			}
			
			
		}
		if(!mainRCMap.isEmpty())insert mainRCMap.values();
		List<RightsConfirmationList__c> tmp =new List<RightsConfirmationList__c>();
		for (String mainKey : rMap.keySet() ) {
			
			Id  mainId = mainMap.get(mainKey) ;
			if(mainId == null ) mainId = mainRCMap.get(mainKey).Id;
			for (RightsConfirmationList__c rc   : rMap.get(mainKey) ) {
				//if(exMap.containsKey(rc.Only__c)) rc.Id = exMap.get(rcf.Only__c);

				 rc.RightsConfirmation__c = mainId ;
				//匹配人员
				String key = getLastQuaterYear(rc.Year__c,rc.Quarter__c) +'-'+getLastQuater(rc.Quarter__c)+'-'+rc.AccountPK__c+'-'+rc.TerminalPK__c +'-'+rc.Company__c+'-'+rc.Province__c ;
				PerformanceRightsConfirmation__c prc = prMap.get(key);
				
				if(rc.DirectBusinessOwner__c == null )rc.DirectBusinessOwner__c = prc != null ?  prc.DirectBusinessOwner__c : null ;
				if(rc.DirectBusinessOwnerManager__c == null )rc.DirectBusinessOwnerManager__c = prc != null ?  prc.DirectBusinessOwnerManager__c : null ;
				//分销
				if(rc.DistributionOwner__c == null )rc.DistributionOwner__c = prc != null ?  prc.DistributionOwner__c : null ;
				if(rc.DistributionOwnerManager__c == null )rc.DistributionOwnerManager__c = prc != null ?  prc.DistributionOwnerManager__c : null ;
				
				if(rc.TripartiteOwnerManager__c == null )rc.TripartiteOwnerManager__c = prc != null ?  prc.TripartiteOwnerManager__c : null ;
				if(rc.TripartiteOwner__c == null )rc.TripartiteOwner__c = prc != null ?  prc.TripartiteOwner__c : null ;
				//生化
				if(rc.BiochemicalIOwner__c == null )rc.BiochemicalIOwner__c = prc != null ? prc.BiochemicalIOwner__c : null;
				if(rc.BiochemicalIOwnerManager__c == null )rc.BiochemicalIOwnerManager__c = prc != null ? prc.BiochemicalIOwnerManager__c : null;
				//免疫
				if(rc.ImmunityOwner__c == null )rc.ImmunityOwner__c = prc != null ? prc.ImmunityOwner__c : null;
				if(rc.ImmunityOwnerManager__c == null )rc.ImmunityOwnerManager__c = prc != null ? prc.ImmunityOwnerManager__c :null;
				//临检
				if(rc.ClinicalLaboratoryOwner__c == null )rc.ClinicalLaboratoryOwner__c = prc != null ? prc.ClinicalLaboratoryOwner__c : null;
				if(rc.ClinicalLaboratoryOwnerManager__c == null )rc.ClinicalLaboratoryOwnerManager__c = prc != null ? prc.ClinicalLaboratoryOwnerManager__c :null;
				//病理
				if(rc.PathologyOwner__c == null )rc.PathologyOwner__c = prc != null ? prc.PathologyOwner__c : null;
				if(rc.PathologyOwnerManager__c == null )rc.PathologyOwnerManager__c = prc != null ? prc.PathologyOwnerManager__c :null;
				//POCT
				if(rc.POCTOwner__c == null )rc.POCTOwner__c = prc != null ? prc.POCTOwner__c : null;
				if(rc.POCTOwnerManager__c == null )rc.POCTOwnerManager__c = prc != null ? prc.POCTOwnerManager__c :null;
				//省区管理人员
				if(rc.ProvinceManager__c == null )rc.ProvinceManager__c = prc != null ? prc.ProvinceManager__c :null;

				   //希森美康
            	if(rc.SysmexOwner__c == null )rc.SysmexOwner__c = prc != null ? prc.SysmexOwner__c : null;
				if(rc.SysmexOwnerManager__c == null )rc.SysmexOwnerManager__c = prc != null ? prc.SysmexOwnerManager__c :null;
            	//微生物
            	if(rc.MicrobeOwner__c == null )rc.MicrobeOwner__c = prc != null ? prc.MicrobeOwner__c : null;
				if(rc.MicrobeOwnerManager__c == null )rc.MicrobeOwnerManager__c = prc != null ? prc.MicrobeOwnerManager__c :null;

				//bd BDOwnerManager__c,BDOwner__c,
				if(rc.BDOwner__c == null )rc.BDOwner__c = prc != null ? prc.BDOwner__c : null;
				if(rc.BDOwnerManager__c == null )rc.BDOwnerManager__c = prc != null ? prc.BDOwnerManager__c :null;
				//分子
				if(rc.MolecularOwnerManager__c == null )rc.MolecularOwnerManager__c = prc != null ? prc.MolecularOwnerManager__c : null;
				if(rc.MolecularOwner__c == null )rc.MolecularOwner__c = prc != null ? prc.MolecularOwner__c : null;

				//匹配客户
				rc.Account__c = accMap.get(rc.AccountPK__c);
				if(rc.Account__c == null) accIdMap.get(rc.AccountPK__c);
				rc.TerminalAccount__c =  accMap.get(rc.TerminalPK__c);
				if(rc.TerminalAccount__c == null) accIdMap.get(rc.TerminalPK__c);

				tmp.add(rc);
			}
			
		}
		//upsert tmp;



	}

	private static String getLastQuater(String quater){
		if(quater == '1')return '4';
		return (Integer.valueOf(quater)-1)+'';
	}
	private static String getLastQuaterYear(String year, String quater){
		if(quater == '1')return (Integer.valueOf(year.substring(0,4))-1)+'年';
		return year;

	}
    
}